package com.crm.model.dto;

import com.alibaba.fastjson.JSONObject;
import com.crm.common.model.Enum.StatusCodeEnum;
import com.crm.common.util.CommonUtils;
import com.crm.model.entity.contractManager.CustomerContract;
import com.crm.model.entity.customerManager.Customer;
import com.crm.model.entity.finishOrderProduct.FinishOrderProduct;
import com.crm.model.entity.orderManager.CustomerProductOrder;
import com.crm.model.entity.orderManager.CustomerProductOrderDetail;
import com.crm.model.entity.productManager.CustomerMemberProduct;
import com.crm.model.entity.productManager.CustomerProduct;
import com.crm.model.entity.sys.ImportFailureLog;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.entity.sys.UserInfo;
import com.crm.model.entity.sys.permissionManagement.SysCompany;
import com.crm.model.vo.orderManager.CustomerProductOrderImportVO;
import com.crm.service.contractManager.CustomerContractDbService;
import com.crm.service.customerManager.CustomerDbService;
import com.crm.service.orderManager.CustomerProductOrderDbService;
import com.crm.service.orderManager.CustomerProductOrderDetailDbService;
import com.crm.service.productManager.CustomerMemberProductDbService;
import com.crm.service.productManager.CustomerProductDbService;
import com.crm.service.returnMoney.FinishOrderDBservice;
import com.crm.service.sys.ImportFailureLogDbService;
import com.crm.service.sys.UserInfoDbService;
import com.crm.service.sys.permissionManagement.SysCompanyDbService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;

/**
 * @ Author ：pym
 * @ Date   ：2021/6/1 11:14
 */
@Slf4j
public class InsertCustomerProductOrderCallable implements Callable<JSONObject> {
    private CustomerProductOrderDbService customerProductOrderDbService;
    private ImportFailureLogDbService importFailureLogDbService;
    private CustomerDbService customerDbService;
    private CustomerContractDbService customerContractDbService;
    private CustomerMemberProductDbService memberProductDbService;
    private CustomerProductDbService customerProductDbService;
    private CustomerProductOrderDetailDbService customerProductOrderDetailDbService;
    private FinishOrderDBservice finishOrderDBservice;
    private UserInfoDbService userInfoDbService;
    private SysCompanyDbService sysCompanyDbService;
    private List<CustomerProductOrderImportVO> list;
    private CountDownLatch begin;
    private CountDownLatch end;
    private Integer index;

    public InsertCustomerProductOrderCallable(CustomerProductOrderDbService customerProductOrderDbService,
                                              ImportFailureLogDbService importFailureLogDbService,
                                              CustomerDbService customerDbService,
                                              CustomerContractDbService customerContractDbService,
                                              CustomerMemberProductDbService memberProductDbService,
                                              CustomerProductDbService customerProductDbService,
                                              CustomerProductOrderDetailDbService customerProductOrderDetailDbService,
                                              FinishOrderDBservice finishOrderDBservice, UserInfoDbService userInfoDbService,
                                              SysCompanyDbService sysCompanyDbService, List<CustomerProductOrderImportVO> list,
                                              CountDownLatch begin, CountDownLatch end, Integer index) {
        this.customerProductOrderDbService = customerProductOrderDbService;
        this.importFailureLogDbService = importFailureLogDbService;
        this.customerDbService = customerDbService;
        this.customerContractDbService = customerContractDbService;
        this.memberProductDbService = memberProductDbService;
        this.customerProductDbService = customerProductDbService;
        this.customerProductOrderDetailDbService = customerProductOrderDetailDbService;
        this.finishOrderDBservice = finishOrderDBservice;
        this.userInfoDbService = userInfoDbService;
        this.sysCompanyDbService = sysCompanyDbService;
        this.list = list;
        this.begin = begin;
        this.end = end;
        this.index = index;
    }

    /**
     * 订单导入
     * @Author pym
     * @Date  2021/6/1 16:58
     * @param
     * @return {@link {com.alibaba.fastjson.JSONObject}}
     */
    @Override
    public JSONObject call() throws Exception {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        String operatePeopleId = userAccount.getAccountId();
        int importNum = 0;//导入数量
        List<Integer> repeatIdStr = new ArrayList();//重复的行数
        List<Integer> importFailIdStr = new ArrayList();//失败行数
        List<Integer> contractNotExist = new ArrayList();//合同不存在行数
        List<Integer> customerNotExist = new ArrayList();//客户不存在行数
        List<Integer> otherOrders = new ArrayList();//只导入回款状态为已回款并且订单状态为生效中或者已结束的订单，其它的订单需手工录入
        List<Integer> ownerNull = new ArrayList();//所有人不存在
        for (int i = 0; i < list.size(); i++) {
            CustomerProductOrderImportVO customerProductOrderImportVO = list.get(i);
            String orderStatus = customerProductOrderImportVO.getOrderStatus();//订单状态
            String paidBackStatus = customerProductOrderImportVO.getPaidBackStatus();//回款状态
            //公司id
            String companyId = "";
            //所有人id
            String accountId = "";
            //订单编号
            String orderNumber = customerProductOrderImportVO.getOrderNumber();
            int j = (i + 2) + index * 100;
            try {
                String companyName = customerProductOrderImportVO.getCompany();//所属分公司
                SysCompany sysCompany = null;
                if (StringUtils.isNotBlank(companyName)) {
                    sysCompany = sysCompanyDbService.selectSysCompanyByName(companyName);
                }
                //查询所有人是否存在
                String owner = customerProductOrderImportVO.getOwner();
                UserInfo userInfo = null;
                if (!StringUtils.isBlank(owner)) {
                    userInfo = userInfoDbService.getUserInfoByUserNameAndCompanyName(owner,customerProductOrderImportVO.getCompany());
                }
                String sysCompanyId = sysCompany != null ? sysCompany.getCompanyId() : "";
                //公司id
                companyId = userInfo != null ? userInfo.getCompanyId() : sysCompanyId;
                //所有人id
                accountId = userInfo != null ? userInfo.getAccountId() : "";

                Boolean insertLog = true;
                String importErrorData = "0";
                //只导入回款状态为已回款并且订单状态为生效中或者已结束的订单，其它的订单需手工录入
                if (!"已回款".equals(paidBackStatus) && !("生效中".equals(orderStatus) || "已结束".equals(orderStatus))) {
                    otherOrders.add(i+2);
                    Boolean result = importFailureLogDbService.selectImportFailureLogByExample("3",orderNumber,companyId,accountId,customerProductOrderImportVO != null ? customerProductOrderImportVO.toString() : "");
                    if(!result){
                        importFailureLogDbService.insertImportFailureLog(getImportFailureLog(operatePeopleId, customerProductOrderImportVO, "3", "第" +j+ "行，订单状态为："+orderStatus+"，不导入",null,null,"4",companyId,accountId));
                    }
                    continue;
                }
                if (userInfo == null) {
                    if (insertLog) {
                        //ownerNull.add(i+2);
                        importErrorData = "1";
                        Boolean result = importFailureLogDbService.selectImportFailureLogByExample("3",orderNumber,companyId,accountId,customerProductOrderImportVO != null ? customerProductOrderImportVO.toString() : "");
                        if(!result){
                            importFailureLogDbService.insertImportFailureLog(getImportFailureLog(operatePeopleId, customerProductOrderImportVO, "3", "第" +j+ "行，订单所有人："+owner+"，不存在",null,null,"3",companyId,accountId));
                            insertLog = false;
                        }
                    }
                }
                CustomerProductOrder isCustomerProductOrderRepeat = customerProductOrderDbService.isCustomerProductOrderRepeat(orderNumber);
                if (isCustomerProductOrderRepeat != null) {//订单重复
                    repeatIdStr.add(i+2);
/*                    Boolean result = importFailureLogDbService.selectImportFailureLogByExample("3",orderNumber,companyId,accountId,customerProductOrderImportVO != null ? customerProductOrderImportVO.toString() : "");
                    if(!result){
                        importFailureLogDbService.insertImportFailureLog(getImportFailureLog(operatePeopleId, customerProductOrderImportVO, "3", "第" +j+ "行，订单重复",isCustomerProductOrderRepeat.getProductOrderId(),null,"1",companyId,accountId));
                    }*/
                    continue;
                }
                String customerName = customerProductOrderImportVO.getCustomerName();//客户名称
                Customer customer = null;
                if (userInfo != null && userInfo.getAccountId() != null) {
                    customer = customerDbService.selectCustomerByNameAndId(customerName, userInfo.getAccountId());
                }
                if (customer == null) {//客户不存在
                    if (insertLog) {
                        //customerNotExist.add(i+2);
                        importErrorData = "1";
                        Boolean result = importFailureLogDbService.selectImportFailureLogByExample("3",orderNumber,companyId,accountId,customerProductOrderImportVO != null ? customerProductOrderImportVO.toString() : "");
                        if(!result){
                            importFailureLogDbService.insertImportFailureLog(getImportFailureLog(operatePeopleId, customerProductOrderImportVO, "3", "第" +j+ "行，"+customerName+"，客户不存在",null,null,"3",companyId,accountId));
                            insertLog = false;
                        }
                    }
                }
                String contractNumber = customerProductOrderImportVO.getContractNumber();//所属合同
                if (StringUtils.isNotBlank(contractNumber)) {//所属合同不为空 会员合同
                    CustomerContract customerContract = customerContractDbService.selectContractByContractNumber(contractNumber);
                    if (customerContract == null) {//合同不存在
                        if (insertLog) {
                            //contractNotExist.add(i+2);
                            importErrorData = "1";
                            Boolean result = importFailureLogDbService.selectImportFailureLogByExample("3",orderNumber,companyId,accountId,customerProductOrderImportVO != null ? customerProductOrderImportVO.toString() : "");
                            if(!result){
                                importFailureLogDbService.insertImportFailureLog(getImportFailureLog(operatePeopleId, customerProductOrderImportVO, "3", "第" +j+ "行，"+ contractNumber+"，合同不存在",null,null,"3",companyId,accountId));
                                insertLog = false;
                            }
                        }
                    }
                    CustomerProductOrder customerProductOrder = getCustomerProductOrder(customerProductOrderImportVO, userAccount, customer, customerContract, userInfo, sysCompany, importErrorData);
                    if (!customerProductOrderDbService.insertProductOrder(customerProductOrder)) {//导入失败
                        importFailIdStr.add(i+2);
                        Boolean result = importFailureLogDbService.selectImportFailureLogByExample("3",orderNumber,companyId,accountId,customerProductOrderImportVO != null ? customerProductOrderImportVO.toString() : "");
                        if(!result){
                            importFailureLogDbService.insertImportFailureLog(getImportFailureLog(operatePeopleId, customerProductOrderImportVO, "3", "第" +j+ "行，" + "插入数据失败",null,null,"2",companyId,accountId));
                        }
                        continue;
                    }
                    importNum = importNum + 1;//导入成功
                    //更新合同表中订单id
                    if (customerContract != null) {
                        customerContract.setOrderId(customerProductOrder.getProductOrderId());
                        customerContractDbService.updateCustomerContract(customerContract);
                    }
                    CustomerMemberProduct customerMemberProduct = getCustomerMemberProduct(customerProductOrderImportVO, userAccount, i);//获取会员产品，如果不存在就新增
                    CustomerProductOrderDetail customerProductOrderDetail = getCustomerProductOrderDetail(userAccount, customerProductOrder, customerMemberProduct, null, "1");//获取产品订单明细
                    customerProductOrderDetailDbService.insertCustomerProductOrderDetail(customerProductOrderDetail);//新增产品订单明细
                    FinishOrderProduct finishOrderProduct = getFinishOrderProduct(i, customerProductOrder, customerMemberProduct, null, customerProductOrderDetail, "1", customerContract);//获取订单完成的产品
                    finishOrderDBservice.insertFinishOrderProduct(finishOrderProduct);//新增订单完成的产品
                } else {//所属合同为空 非会员合同
                    CustomerContract customerContract = getCustomerContract(customerProductOrderImportVO, customer, userAccount, userInfo, sysCompany, i);//获取非会员合同
                    CustomerProductOrder customerProductOrder = getCustomerProductOrder(customerProductOrderImportVO, userAccount, customer, customerContract, userInfo, sysCompany, importErrorData);
                    customerContract.setOrderId(customerProductOrder.getProductOrderId());
                    customerContractDbService.insertCustomerContract(customerContract);//新增非会员合同
                    if (!customerProductOrderDbService.insertProductOrder(customerProductOrder)) {//导入失败
                        importFailIdStr.add(i+2);
                        Boolean result = importFailureLogDbService.selectImportFailureLogByExample("3",orderNumber,companyId,accountId,customerProductOrderImportVO != null ? customerProductOrderImportVO.toString() : "");
                        if(!result){
                            importFailureLogDbService.insertImportFailureLog(getImportFailureLog(operatePeopleId, customerProductOrderImportVO, "3", "第" +j+ "行，" + "插入数据失败",null,null,"2",companyId,accountId));
                        }
                        continue;
                    }
                    importNum = importNum + 1;//导入成功
                    CustomerProduct customerProduct = getCustomerProduct(customerProductOrderImportVO, userAccount, i);//获取非会员产品，如果不存在就新增
                    CustomerProductOrderDetail customerProductOrderDetail = getCustomerProductOrderDetail(userAccount, customerProductOrder, null, customerProduct, "0");//获取产品订单明细
                    customerProductOrderDetailDbService.insertCustomerProductOrderDetail(customerProductOrderDetail);//新增产品订单明细
                    FinishOrderProduct finishOrderProduct = getFinishOrderProduct(i, customerProductOrder, null, customerProduct, customerProductOrderDetail, "0", customerContract);//获取订单完成的产品
                    finishOrderDBservice.insertFinishOrderProduct(finishOrderProduct);//新增订单完成的产品
                }
            } catch (Exception e) {//导入失败
                importFailIdStr.add(i+2);
                Boolean result = importFailureLogDbService.selectImportFailureLogByExample("3",orderNumber,companyId,accountId,customerProductOrderImportVO != null ? customerProductOrderImportVO.toString() : "");
                if(!result){
                    importFailureLogDbService.insertImportFailureLog(getImportFailureLog(operatePeopleId, customerProductOrderImportVO, "3", "第" +j+ "行，" + "导入异常",null,getExceptionPrintStackTrace(e),"2",companyId,accountId));
                }
                log.error("InsertCustomerProductOrderCallable importCustomerProductOrder error:", e);
            }
            end.countDown();
        }
        JSONObject result = new JSONObject();
        result.put("importNum",importNum);
        result.put("repeatIdStr",repeatIdStr);
        result.put("importFailIdStr",importFailIdStr);
        result.put("contractNotExist",contractNotExist);
        result.put("customerNotExist",customerNotExist);
        result.put("otherOrders",otherOrders);
        result.put("ownerNull",ownerNull);
        return result;
    }

    /**
     * 获取订单
     * @Author pym
     * @Date  2021/6/1 16:58
     * @param customerProductOrderImportVO 订单信息
     * @return {@link {com.crm.model.entity.orderManager.CustomerProductOrder}}
     */
    private CustomerProductOrder getCustomerProductOrder(CustomerProductOrderImportVO customerProductOrderImportVO,
                                                         UserAccount userAccount, Customer customer,
                                                         CustomerContract customerContract, UserInfo userInfo,
                                                         SysCompany sysCompany, String importErrorData) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        // 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期，比如2018-02-29会被接受，并转换成2018-03-01
        format.setLenient(false);
        SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");
        date.setLenient(false);
        CustomerProductOrder customerProductOrder = new CustomerProductOrder();
        customerProductOrder.setProductOrderId(CommonUtils.getGUID());
        customerProductOrder.setOrderType(customerContract != null ? customerContract.getWhetherCheck() : "");//订单类型--0:非会员订单;1:会员订单（创建维护）
        customerProductOrder.setOrderPaymentWay(customerContract != null ? customerContract.getPaymentMethod() : "");//支付方式--1:线上支付;2:线下支付;3:余额支付;4:银行汇款 （创建维护）
        //customerProductOrder.setOrderDiscountTotalAmount();//订单优惠总金额
        String actualTransactionPrice = customerProductOrderImportVO.getActualTransactionPrice();
        if (StringUtils.isNotBlank(actualTransactionPrice)) {
            BigDecimal decimal = new BigDecimal(actualTransactionPrice);
            customerProductOrder.setOrderActualTotalAmount(decimal.setScale(2,BigDecimal.ROUND_HALF_UP));//订单实际总金额 （创建   退款维护）
            customerProductOrder.setOrderTotalAmount(decimal.setScale(2,BigDecimal.ROUND_HALF_UP));//订单总金额
        }
        String paidBackAmount = customerProductOrderImportVO.getPaidBackAmount();
        if (StringUtils.isNotBlank(paidBackAmount)) {
            BigDecimal decimal = new BigDecimal(paidBackAmount);
            customerProductOrder.setPaidBackAmount(decimal.setScale(2,BigDecimal.ROUND_HALF_UP));//已回款金额合计 （回款维护）
        }
        customerProductOrder.setOrderSurcharge(new BigDecimal("0.00"));//附加费用
        //customerProductOrder.setOrderSurchargeRemark();//附加费用备注
        //customerProductOrder.setContactPerson();//客户联系人
        //customerProductOrder.setBindMobilePhoneNumber();//客户联系方式
        //customerProductOrder.setCustomerEmail();//客户邮箱
        customerProductOrder.setContractType(customerContract != null ? customerContract.getContractType() : "");//合同类型--0:非会员合同;1:会员新单合同;2:会员续费合同;3:课程合同;4:从属合同;5:其他合同;6:单品合同
        customerProductOrder.setWhetherCoDevelopment("2");//是否合作开发--1:是;2:否
        customerProductOrder.setOrderNumber(customerProductOrderImportVO.getOrderNumber());//订单编号
        customerProductOrder.setWhetherSuspend("2");//是否挂起--1:是;2-否
        String paidBackStatus = customerProductOrderImportVO.getPaidBackStatus();
        //订单状态--1:等待回款;2:已完成;3:作废;4:部分回款（回款维护）
        customerProductOrder.setOrderStatus("2");
        String dateOfPayment = customerProductOrderImportVO.getDateOfPayment();//到款日期
        if (isValidDate(dateOfPayment,"yyyy-MM-dd")) {
            customerProductOrder.setOrderCompleteTm(date.parse(dateOfPayment));//订单完成时间
        } else {
            customerProductOrder.setOrderCompleteTm(new Date());
        }
        customerProductOrder.setContractId(customerContract != null ? customerContract.getContractId() : "");
        customerProductOrder.setContractNumber(customerProductOrderImportVO.getContractNumber());//合同编号
        String companyId = sysCompany != null ? sysCompany.getCompanyId() : "";
        customerProductOrder.setAffiliationCompanyId(userInfo != null ? userInfo.getCompanyId() : companyId);//所属分公司--关联公司表ID
        customerProductOrder.setCustomerId(customer != null ? customer.getCustomerId() : "");//客户ID--关联客户表主键
        customerProductOrder.setCustomerName(customer != null ? customer.getCustomerName() : "");//客户名称
        customerProductOrder.setCreatePeopleId(userInfo != null ? userInfo.getAccountId() : "");//所有人
        String createTm = customerProductOrderImportVO.getCreateTm();
        if (isValidDate(createTm,"yyyy-MM-dd HH:mm")) {
            customerProductOrder.setCreateTm(format.parse(createTm));
        } else {
            customerProductOrder.setCreateTm(new Date());
        }
        customerProductOrder.setUpdatePeopleId(userAccount.getAccountId());
        customerProductOrder.setUpdateTm(new Date());
        customerProductOrder.setOldOrder("1");//是否是老订单：0:否；1:是
        //提成发放状态（1:已全部发放；2:部分发放;3:未发放）
        String commissionStatus = customerProductOrderImportVO.getCommissionStatus();
        if ("已全部发放".equals(commissionStatus)) {
            customerProductOrder.setRoyaltyStatus("1");
        } else if ("部分发放".equals(commissionStatus)) {
            customerProductOrder.setRoyaltyStatus("2");
        }  else if ("未发放".equals(commissionStatus)) {
            customerProductOrder.setRoyaltyStatus("3");
        }
        customerProductOrder.setImportErrorData(importErrorData);//是否是导入时出错数据：0:否；1:是
        return customerProductOrder;
    }

    /**
     * 判断一个字符串是否为合法日期
     * @Author pym
     * @Date  2021/4/28 16:33
     * @param strDate -字符串
     * @return {@link {boolean}}
     */
    public boolean isValidDate(String strDate, String format) {
        boolean convertSuccess = true;
        SimpleDateFormat formatter  = new SimpleDateFormat(format);
        try {
            // 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期，比如2018-02-29会被接受，并转换成2018-03-01
            formatter.setLenient(false);
            Date date = formatter.parse(strDate);
        } catch (Exception e) {
            // e.printStackTrace();
            // 如果throw java.text.ParseException或者NullPointerException，就说明格式不对
            convertSuccess = false;
        }
        return convertSuccess;
    }

    /**
     * 获取异常信息
     * @Author pym
     * @Date  2021/5/27 16:05
     * @param e 异常
     * @return {@link {java.lang.String}}
     */
    private static String getExceptionPrintStackTrace(Exception e){
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw, true);
        e.printStackTrace(pw);
        pw.flush();
        sw.flush();
        return sw.toString();
    }

    /**
     * 获取导入失败日志
     * @Author pym
     * @Date  2021/6/2 8:59
     * @param accountId 账号ID
     * @param customerProductOrderImportVO 订单信息
     * @param operateType 导入什么业务：1-线索；2-客户；3-订单；
     * @param reasonForFailure 失败原因
     * @param dataId 重复数据ID:客户ID/订单ID
     * @param exceptionLog 异常日志
     * @param logType 日志类型：1-重复日志；2.异常日志
     * @return {@link {com.crm.model.entity.sys.ImportFailureLog}}
     */
    private ImportFailureLog getImportFailureLog(String operatePeopleId, CustomerProductOrderImportVO customerProductOrderImportVO,
                                                 String operateType, String reasonForFailure, String dataId,
                                                 String exceptionLog, String logType,String companyId,String accountId) {
        ImportFailureLog importFailureLog = new ImportFailureLog();
        importFailureLog.setImportFailureLogId(CommonUtils.getGUID());
        importFailureLog.setOperatePeopleId(operatePeopleId);
        importFailureLog.setOperateTime(new Date());
        importFailureLog.setOperateType(operateType);
        importFailureLog.setImportName(customerProductOrderImportVO != null ? customerProductOrderImportVO.getOrderNumber() : "");
        importFailureLog.setReasonForFailure(reasonForFailure);
        importFailureLog.setImportData(customerProductOrderImportVO != null ? customerProductOrderImportVO.toString() : "");
        importFailureLog.setDataId(dataId);
        importFailureLog.setExceptionLog(exceptionLog);
        importFailureLog.setLogType(logType);
        importFailureLog.setCompanyId(companyId);
        importFailureLog.setAccountId(accountId);
        return importFailureLog;
    }

    /**
     * 获取会员产品，如果不存在就新增
     * @Author pym
     * @Date  2021/6/3 15:20
     * @param customerProductOrderImportVO 订单信息
     * @param userAccount 账户信息
     * @return {@link {com.crm.model.entity.productManager.CustomerMemberProduct}}
     */
    private CustomerMemberProduct getCustomerMemberProduct(CustomerProductOrderImportVO customerProductOrderImportVO, UserAccount userAccount, int i) throws Exception {
        //根据会员卡名称或者会员产品编码查询会员产品信息是否存在
        String products = customerProductOrderImportVO.getProducts();//购买产品
        String productCode = customerProductOrderImportVO.getProductCode();//产品编码
        if (StringUtils.isBlank(products)) {
            return null;
        }
        CustomerMemberProduct memberProduct = memberProductDbService.selectMemberProductByNameOrCode(products, productCode);
        if (memberProduct != null) {
            return memberProduct;
        }
        //添加会员产品(chs_customer_member_product)
        CustomerMemberProduct customerMemberProduct = new CustomerMemberProduct();
        customerMemberProduct.setMemberProductId(CommonUtils.getGUID());//主键
        customerMemberProduct.setMemberCardName(products);//会员卡名称
        String productCodeStr = String.valueOf(new Date().getTime()) + i;
        customerMemberProduct.setMemberProductCode(StringUtils.isNotBlank(productCode) ? productCode : productCodeStr);//产品编码
        String productUnitPrice = customerProductOrderImportVO.getProductUnitPrice();//产品单价
        if (StringUtils.isNotBlank(productUnitPrice)) {
            BigDecimal decimal = new BigDecimal(productUnitPrice);
            customerMemberProduct.setSellingCardPrice(decimal.setScale(2,BigDecimal.ROUND_HALF_UP));//售卡价格
        }
        //customerMemberProduct.setServiceNumber(); //会员服务总次数
        //customerMemberProduct.setProductMembershipLevel(); //会员等级
        //customerMemberProduct.setMemberCardImg();//会员图片
        //customerMemberProduct.setProductPeriodValidityStart();//产品有效期起始日期
        //customerMemberProduct.setProductPeriodValidityEnd();//产品有效期截止日期
        customerMemberProduct.setWhetherIncludedAchievement("0");
        customerMemberProduct.setDeleteStatus((short)StatusCodeEnum.NORMAL_CODE.getState());//删除状态
        customerMemberProduct.setCreatePeopleId(userAccount.getAccountId());//创建人ID
        customerMemberProduct.setCreateTm(new Date());//创建时间
        customerMemberProduct.setUpdatePeopleId(userAccount.getAccountId());//更新人ID
        customerMemberProduct.setUpdateTm(new Date());//更新时间
        customerMemberProduct.setProductStatus("0");//停、启用状态--0:启用;1:停用
        Boolean result = memberProductDbService.insertCustomerMemberProduct(customerMemberProduct);
        if (result) {
            return customerMemberProduct;
        }
        return null;
    }

    /**
     * 获取非会员产品，如果不存在就新增
     * @Author pym
     * @Date  2021/6/3 16:08
     * @param customerProductOrderImportVO 订单信息
     * @param userAccount 账户信息
     * @return {@link {com.crm.model.entity.productManager.CustomerProduct}}
     */
    public CustomerProduct getCustomerProduct(CustomerProductOrderImportVO customerProductOrderImportVO, UserAccount userAccount, int i) {
        String products = customerProductOrderImportVO.getProducts();//购买产品
        String productCode = customerProductOrderImportVO.getProductCode();//产品编码
        if (StringUtils.isBlank(products)) {
            return null;
        }
        CustomerProduct product = customerProductDbService.selectCustomerProductByNameOrCode(products, productCode);
        if (product != null) {
            return product;
        }
        CustomerProduct customerProduct =new CustomerProduct();
        customerProduct.setCustomerProductId(CommonUtils.getGUID());//主键
        customerProduct.setProductName(products);//产品名称
        String productCodeStr = String.valueOf(new Date().getTime()) + i;
        customerProduct.setProductCode(StringUtils.isNotBlank(productCode) ? productCode : productCodeStr);//产品编码
        //customerProduct.setServiceClassification();//服务分类
        //customerProduct.setProductTag();//产品标签
        //customerProduct.setProductOriginalPrice();//产品原价
        String productUnitPrice = customerProductOrderImportVO.getProductUnitPrice();
        if (StringUtils.isNotBlank(productUnitPrice)) {
            BigDecimal decimal = new BigDecimal(productUnitPrice);
            customerProduct.setProductUnitPrice(decimal.setScale(2,BigDecimal.ROUND_HALF_UP));//产品单价
        }
        //customerProduct.setPerformanceConversionRatio();//业绩换算比例
        //customerProduct.setProductMemberPrice();//产品会员价
        //customerProduct.setTopicId();//专题ID
        //customerProduct.setStudyPeriod();//学习期数
        //customerProduct.setExchangeMethod();//兑换方式
        //customerProduct.setProductDesc();//产品描述
        //customerProduct.setProductManual();//产品说明
        customerProduct.setCreateTm(new Date());//创建时间
        customerProduct.setCreatePeopleId(userAccount.getAccountId());//创建人
        customerProduct.setUpdatePeopleId(userAccount.getAccountId());//更新人ID
        customerProduct.setUpdateTm(new Date());//更新时间
        customerProduct.setDeleteStatus((short)StatusCodeEnum.NORMAL_CODE.getState());//删除状态
        customerProduct.setShelfStatus("0");//(上/下架状态:待定)
        Boolean result = customerProductDbService.insertCustomerProduct(customerProduct);
        if (result) {
            return customerProduct;
        }
        return null;
    }

    /**
     * 获取非会员合同
     * @Author pym
     * @Date  2021/6/3 17:50
     * @param customerProductOrderImportVO 订单信息
     * @param customer 客户信息
     * @param userAccount 账号信息
     * @return {@link {com.crm.model.entity.contractManager.CustomerContract}}
     */
    private CustomerContract getCustomerContract(CustomerProductOrderImportVO customerProductOrderImportVO, Customer customer, UserAccount userAccount,
                                                 UserInfo userInfo, SysCompany sysCompany, int i) throws Exception {
        SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");
        // 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期，比如2018-02-29会被接受，并转换成2018-03-01
        date.setLenient(false);
        CustomerContract customerContract = new CustomerContract();
        customerContract.setContractId(CommonUtils.getGUID());//合同id
        String contractNumber = String.valueOf(new Date().getTime()) + i;
        customerContract.setContractNumber(contractNumber);//合同编号
        customerContract.setContractStatus("2");//合同状态生效中
        customerContract.setCustomerId(customer != null ? customer.getCustomerId() : "");//客户ID
        customerContract.setCustomerName(customer != null ? customer.getCustomerName()  : "");//客户名称
        customerContract.setContractType("1");//合同类型--1:非会员合同;2:会员新单合同;3:活动合同;4:会员续费合同5.兑换合同6.单品合同
        customerContract.setOldContract("1");//是否是老合同：0:否;1:是
        String contractStartDate = customerProductOrderImportVO.getContractStartDate();//合同开始日期
        if (isValidDate(contractStartDate,"yyyy-MM-dd")) {
            customerContract.setContractStartDate(date.parse(contractStartDate));
        }
        String contractEndDate = customerProductOrderImportVO.getContractEndDate();//合同结束日期
        if (isValidDate(contractStartDate,"yyyy-MM-dd")) {
            customerContract.setContractEndDate(date.parse(contractEndDate));
        }
        String contractReceivables = customerProductOrderImportVO.getActualTransactionPrice();
        if (StringUtils.isNotBlank(contractReceivables)) {
            BigDecimal decimal = new BigDecimal(contractReceivables);
            customerContract.setContractReceivables(decimal.setScale(2,BigDecimal.ROUND_HALF_UP));//合同实际成交金额
        }
        //customerContract.setContractActualTotalAmount();//合同实际总金额
        String paidBackAmount = customerProductOrderImportVO.getPaidBackAmount();
        if (StringUtils.isNotBlank(paidBackAmount)) {
            BigDecimal decimal = new BigDecimal(paidBackAmount);
            customerContract.setContractTotalPaymentAmount(decimal.setScale(2,BigDecimal.ROUND_HALF_UP));//合同总回款金额
        }
        String timesOfPayment = customerProductOrderImportVO.getTimesOfPayment();
        customerContract.setPaymentNumber(isNumeric(timesOfPayment) ? Integer.parseInt(timesOfPayment) : 1);//到款次数
        //只导入回款状态为已回款并且订单状态为生效中或者已结束的订单
        customerContract.setPaymentStatus("1");//回款状态：0-未回款；1-已回款；3-部分回款
        String whetherCooperateDevelopment = customerProductOrderImportVO.getWhetherCooperateDevelopment();//是否合作开发
        if("是".equals(whetherCooperateDevelopment)){
            customerContract.setWhetherCooperateDevelopment("1");
        }else if("否".equals(whetherCooperateDevelopment)){
            customerContract.setWhetherCooperateDevelopment("0");
        }
        String companyId = sysCompany != null ? sysCompany.getCompanyId() : "";
        customerContract.setAffiliationCompanyId(userInfo != null ? userInfo.getCompanyId() : companyId);//所属分公司
        customerContract.setCreatePeopleId(userInfo != null ? userInfo.getAccountId() : "");//所有人
        customerContract.setWhetherCheck("0");//是否会员合同:1 是；0-否
        String paymentMethod = customerProductOrderImportVO.getPaymentMethod();//支付方式
        if("线下支付".equals(paymentMethod)){
            customerContract.setPaymentMethod("2");
        }else if("余额支付".equals(paymentMethod)){
            customerContract.setPaymentMethod("3");
        }
        //customerContract.setContractTotalAmount();//合同总金额
        String commissionStatus = customerProductOrderImportVO.getCommissionStatus();//提成发放状态
        if("已全部发放".equals(commissionStatus)){
            customerContract.setCommissionStatus("1");
        }else if("已部分发放".equals(commissionStatus)){
            customerContract.setCommissionStatus("2");
        }else if("未发放".equals(commissionStatus)){
            customerContract.setCommissionStatus("3");
        }
        //customerContract.setContractRenewal();//合同续费
        customerContract.setContractCategory(0);//合同分类先算到合同列表中
        customerContract.setCreateTm(new Date());//创建时间
        //customerContract.setCreatePeopleId(userAccount.getAccountId());//创建人
        customerContract.setUpdatePeopleId(userAccount.getAccountId());//更新人ID
        customerContract.setUpdateTm(new Date());//更新时间
        customerContract.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));//删除状态
        /*Boolean insertResult = customerContractDbService.insertCustomerContract(customerContract);
        if (insertResult) {
            return customerContract;
        }
        return null;*/
        customerContract.setWhetherHang("0");//是否挂起:1-是；0-否
        return customerContract;
    }

    /**
     * 判断一个字符串是否为数字型
     * @Author pym
     * @Date  2021/6/4 14:36
     * @param str 字符串
     * @return {@link {boolean}}
     */
    private boolean isNumeric(String str){
        for (int i = str.length();--i>=0;){
            if (!Character.isDigit(str.charAt(i))){
                return false;
            }
        }
        return true;
    }

    /**
     * 获取产品订单明细
     * @Author pym
     * @Date  2021/6/4 9:10
     * @param userAccount 账号信息
     * @param customerProductOrder 订单
     * @param customerMemberProduct 会员产品
     * @param customerProduct 非会员产品
     * @param productCategories 产品分类:0:非会员:1:会员；
     * @return {@link {com.crm.model.entity.orderManager.CustomerProductOrderDetail}}
     */
    private CustomerProductOrderDetail getCustomerProductOrderDetail(UserAccount userAccount, CustomerProductOrder customerProductOrder,
                                                                     CustomerMemberProduct customerMemberProduct, CustomerProduct customerProduct,
                                                                     String productCategories) {
        CustomerProductOrderDetail customerProductOrderDetail = new CustomerProductOrderDetail();
        customerProductOrderDetail.setProductOrderDetailId(CommonUtils.getGUID());
        customerProductOrderDetail.setProductCategories(productCategories);//产品分类:0:非会员:1:会员；
        //customerProductOrderDetail.setProductOriginalPrice();//原价
        if ("1".equals(productCategories)) {//会员产品
            if (customerMemberProduct != null) {
                customerProductOrderDetail.setOrderDetailName(customerMemberProduct.getMemberCardName());//名称(订单类型：1 则为产品名称；2/3则为活动名称)
                customerProductOrderDetail.setProductCode(customerMemberProduct.getMemberProductCode());//产品编码
                customerProductOrderDetail.setProductMemberPrice(customerMemberProduct.getSellingCardPrice());//会员价
                customerProductOrderDetail.setProductFinalPrice(customerMemberProduct.getSellingCardPrice());//产品成交价
                customerProductOrderDetail.setOrderRelationId(customerMemberProduct.getMemberProductId());//订单-关联产品、活动、赠品活动表主键
            }
        } else if ("0".equals(productCategories)) {//非会员产品
            if (customerProduct != null) {
                customerProductOrderDetail.setOrderDetailName(customerProduct.getProductName());//名称(订单类型：1 则为产品名称；2/3则为活动名称)
                customerProductOrderDetail.setProductCode(customerProduct.getProductCode());//产品编码
                customerProductOrderDetail.setProductUnitPrice(customerProduct.getProductUnitPrice());//单价
                customerProductOrderDetail.setProductFinalPrice(customerProduct.getProductUnitPrice());//产品成交价
                customerProductOrderDetail.setOrderRelationId(customerProduct.getCustomerProductId());//订单-关联产品、活动、赠品活动表主键
            }
        }
        //会员产品的优惠价等于会员价减成交价，要是为负值就默认为零 //非会员产品的优惠价等于产品原价减成交价，要是为负值就默认为零
        customerProductOrderDetail.setProductPreferentialPrice(BigDecimal.ZERO);
        //customerProductOrderDetail.setProductQuantity();//数量
        customerProductOrderDetail.setProductOrderDetailType("1");//订单明细类型--1:产品类型;2:活动类型;3:赠品活动类型
        customerProductOrderDetail.setCreatePeopleId(userAccount.getAccountId());//
        customerProductOrderDetail.setCreateTm(new Date());
        customerProductOrderDetail.setUpdatePeopleId(userAccount.getAccountId());
        customerProductOrderDetail.setUpdateTm(new Date());
        customerProductOrderDetail.setProductOrderId(customerProductOrder.getProductOrderId());
        return customerProductOrderDetail;
    }

    /**
     * 获取订单完成的产品
     * @Author pym
     * @Date  2021/6/4 16:10
     * @param i
     * @param customerProductOrder 订单
     * @param customerMemberProduct 会员产品
     * @param customerProduct 非会员产品
     * @param customerProductOrderDetail 产品订单明细
     * @param productCategories 产品分类:0:非会员:1:会员；
     * @return {@link {com.crm.model.entity.finishOrderProduct.FinishOrderProduct}}
     */
    private FinishOrderProduct getFinishOrderProduct(int i, CustomerProductOrder customerProductOrder,
                                                     CustomerMemberProduct customerMemberProduct, CustomerProduct customerProduct,
                                                     CustomerProductOrderDetail customerProductOrderDetail, String productCategories,
                                                     CustomerContract customerContract) {
        FinishOrderProduct finishOrderProduct = new FinishOrderProduct();
        finishOrderProduct.setFinishOrderProductId(CommonUtils.getGUID());//主键
        finishOrderProduct.setFinishOrderProductNum(String.valueOf(new Date().getTime())+ i);//产品号
        if ("1".equals(productCategories)) {//会员产品
            if (customerMemberProduct != null) {
                finishOrderProduct.setProductId(customerMemberProduct.getMemberProductId());//产品id
                finishOrderProduct.setProductName(customerMemberProduct.getMemberCardName());//产品名称
                finishOrderProduct.setProductCode(customerMemberProduct.getMemberProductCode());//产品编码
                finishOrderProduct.setProductMemberPrice(customerMemberProduct.getSellingCardPrice());//会员价
                finishOrderProduct.setProductCategories(productCategories);//产品分类:0:非会员:1:会员；
            }
        } else if ("0".equals(productCategories)) {//非会员产品
            if (customerProduct != null) {
                finishOrderProduct.setProductId(customerProduct.getCustomerProductId());//产品id
                finishOrderProduct.setProductName(customerProduct.getProductName());//产品名称
                finishOrderProduct.setProductCode(customerProduct.getProductCode());//产品编码
                finishOrderProduct.setProductUnitPrice(customerProduct.getProductUnitPrice());//产品单价
                finishOrderProduct.setProductCategories(productCategories);//产品分类:0:非会员:1:会员；
            }
        }
        finishOrderProduct.setProductCategories(productCategories);
        finishOrderProduct.setOrderDetailType("1");//订单明细类型--1:产品类型;2:活动类型;3:赠品活动类型;4:兑换类型
        //finishOrderProduct.setProductOriginalPrice();//产品原价
        //finishOrderProduct.setProductPreferentialPrice();//优惠价
        finishOrderProduct.setProductFinalPrice(customerProductOrder.getOrderActualTotalAmount());//成交价
        //finishOrderProduct.setProductQuantity();//数量
        //finishOrderProduct.setOrderRelationId();//活动、赠品活动表主键
        finishOrderProduct.setProductOrderId(customerProductOrder.getProductOrderId());//订单id
        finishOrderProduct.setProductOrderDetailId(customerProductOrderDetail.getProductOrderDetailId());//产品订单表id
        //finishOrderProduct.setExchangeMethod();//兑换方式：1-电子卡；2-兑换码；3-学习码；4-充值码;5-税法直通车学习卡;6:其他
        //finishOrderProduct.setRenewalStatus();//是否是续费合同 0 否 1是
        finishOrderProduct.setDelFlag("0");//删除标识 0 未删除 1已删除
        //finishOrderProduct.setProductStrokesServiceNumber();//当前服务次数
        //finishOrderProduct.setProductStrokesIndustryNumber();//当前行业会次数
        finishOrderProduct.setSalesmanId(customerProductOrder.getCreatePeopleId());//所属业务员
        finishOrderProduct.setCompanyId(customerProductOrder.getAffiliationCompanyId());//所属公司
        finishOrderProduct.setOrderNumber(customerProductOrder.getOrderNumber());//订单编号
        finishOrderProduct.setContractNumber(customerContract.getContractNumber());//合同编号
        //finishOrderProduct.setCustomerName();//客户名称
        finishOrderProduct.setContractType(customerContract.getContractType());//合同类型--1:非会员合同;2:会员新单合同;3:活动合同;4:会员续费合同5.兑换合同6.单品合同;7:会员单次合同
        finishOrderProduct.setCreatePeopleId("71902468-8dee-4e30-b554-456d2140c7d9");//创建人ID
        finishOrderProduct.setCreateTm(new Date());
        finishOrderProduct.setUpdatePeopleId("71902468-8dee-4e30-b554-456d2140c7d9");//更新人ID
        finishOrderProduct.setUpdateTm(new Date());
        return finishOrderProduct;
    }

}
